/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.homepage.calendar;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.JsonAssist;
import com.je.common.base.constants.dd.DDType;
import com.je.common.base.mapper.query.Query;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.result.DirectJsonResult;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.StringUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.meta.model.dd.DictionaryItemVo;
import com.je.meta.rpc.dictionary.DictionaryRpcService;
import com.je.meta.service.homepage.calendar.CalendarService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/je/meta/calendar")
public class CalendarController extends AbstractPlatformController {

    private Logger logger = LoggerFactory.getLogger(CalendarController.class);

    @Autowired
    private DictionaryRpcService dictionaryRpcService;
    @Autowired
    private CalendarService calendarService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;

    @Override
    @RequestMapping(value = "/load", method = RequestMethod.POST)
    public BaseRespResult load(BaseMethodArgument param, HttpServletRequest request) {
        String whereSql = param.getWhereSql();
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
//        String permSql = getStringParameter(request, "permSql");
//        String groupSql = getStringParameter(request, "groupSql");
        Calendar cal = Calendar.getInstance();
        //当前日期月份
        cal.add(Calendar.MONTH, 0);
        //创建当前时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        cal.setTime(date);
        //获取到本月起始日
        int actualMinimum = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
        //获取到本月结束日
        int actualMaximum = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置本月起始日的年月日时分秒格式
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), actualMinimum, 00, 00, 00);
        //打印本月起始日的年月日时分秒格式
        String minStart = sdf.format(cal.getTime());
        //设置本月结束日的年月日时分秒格式
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), actualMaximum, 23, 59, 59);
        //打印本月结束日的年月日时分秒格式
        String maxEnd = sdf.format(cal.getTime());

        String startTime = getStringParameter(request, "startTime");
        String endTime = getStringParameter(request, "endTime");

        whereSql += "AND SY_CREATEUSERID='" + SecurityUserHolder.getCurrentAccountRealUserId() + "' AND SY_CREATEORGID = '" + SecurityUserHolder.getCurrentAccountDepartment().getId() + "'";
        if (StringUtil.isNotEmpty(startTime) && StringUtil.isNotEmpty(endTime)) {
            whereSql += "AND ((CALENDAR_STARTTIME >= '" + startTime + "' AND CALENDAR_STARTTIME <= '" + maxEnd + "') OR (CALENDAR_ENDTIME <= '" + endTime + "'AND  CALENDAR_ENDTIME >= '" + minStart + "'))";
        }
        whereSql += "ORDER BY SY_CREATETIME DESC";
        dynaBean.set(BeanService.KEY_WHERE, whereSql);
        ConditionsWrapper wrapper = ConditionsWrapper.builder().table(dynaBean.getTableCode()).apply(whereSql);
        int limit = param.getLimit();
        int pageNum = param.getPage();
        long count = 0L;
        int currentPage = 0;
        int pages = 0;
        List<DynaBean> list;
        if (limit == -1) {
            list = metaService.select(wrapper.getTable(),new Page(-1,-1),wrapper);
            count = list.size();
        } else {
            Page page = new Page(pageNum, limit);
            list = metaService.select(dynaBean.getTableCode(), page, wrapper);
            count = page.getTotal();

        }
        JSONObject returnObj = new JSONObject();
        List<HashMap> values = new ArrayList<>();
        for (DynaBean bean : list) {
            values.add(bean.getValues());
        }
        returnObj.put("rows", values);
        returnObj.put("totalCount", count);
        returnObj.put("currentPage", currentPage);
        returnObj.put("pages", pages);
        return BaseRespResult.successResult(returnObj);
    }


    /**
     * 通过DDCode获取字典项列表 通过系统设置消息推送配置剔除
     *
     */
    @RequestMapping(value = "/getMsDiyDicItem", method = RequestMethod.POST)
    public JSONArray getMsDiyDicItem(BaseMethodArgument param, HttpServletRequest request) {
        //查询条件
        Query query = param.buildQuery();
        //字典编码
        String ddCode = getStringParameter(request, "DICTIONARY_DDCODE");
        DynaBean dictionary = null;
        String ddValueStr = "";
        if (dictionary == null) {
            dictionary = metaService.selectOne("JE_CORE_DICTIONARY", ConditionsWrapper.builder().eq("DICTIONARY_DDCODE", ddCode).eq("DICTIONARY_DDTYPE", DDType.LIST));
        }
        //国际化
        boolean en = false;
        Cookie jeLang = org.springframework.web.util.WebUtils.getCookie(request, "je-local-lang");
        if (jeLang != null) {
            if ("en".equals(jeLang.getValue())) {
                en = true;
            }
        }
        //获取字典项数据
        if (dictionary == null) {
            logger.error("数据字典【" + ddCode + "】未找到!");
            ddValueStr = "[]";
        } else {
            //查询字典项数据
            List<DictionaryItemVo> itemVoList = dictionaryRpcService.buildChildrenList(dictionary, en, query, "");
            String push_platform = systemSettingRpcService.findSettingValue("JE_PUSH_PLATFORM");
            String[] messageTypes = push_platform.split(",");
            ArrayList<DictionaryItemVo> list = CollUtil.newArrayList();
            for (DictionaryItemVo dictionaryItemVo : itemVoList) {
                for (String messageType : messageTypes) {
                    if (dictionaryItemVo.getCode().equals(messageType)) {
                        list.add(dictionaryItemVo);
                    }
                }
            }
            ddValueStr = JSON.toJSONString(list);
        }
        return DirectJsonResult.buildArrayResult(ddValueStr);
    }


    @Override
    @RequestMapping(value = "/doSave", method = RequestMethod.POST)
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        BaseRespResult baseRespResult = super.doSave(param, request);
        try {
            HashMap<String, Object> data = (HashMap<String, Object>) baseRespResult.getData();
            if (StringUtil.isNotEmpty(data.get("CALENDAR_REMIND_TIME").toString())) {
                DynaBean dynaBean = new DynaBean("JE_SYS_CALENDAR_PUSH", false);
                dynaBean.setStr("PUSH_TIME", data.get("CALENDAR_REMIND_TIME").toString());
                dynaBean.setStr("JE_SYS_CALENDAR_ID", data.get("JE_SYS_CALENDAR_ID").toString());
                dynaBean.setStr("PUSH_STARTTIME", data.get("CALENDAR_STARTTIME").toString());
                dynaBean.setStr("PUSH_ENDTIME", data.get("CALENDAR_ENDTIME").toString());
                dynaBean.setStr("PUSH_SFFS_CODE", "1");
                commonService.buildModelCreateInfo(dynaBean);
                metaService.insert(dynaBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return baseRespResult;
    }

    @Override
    @RequestMapping(value = "/doUpdate", method = RequestMethod.POST)
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        BaseRespResult baseRespResult = super.doUpdate(param, request);
        try {
            HashMap<String, Object> data = (HashMap<String, Object>) baseRespResult.getData();
            if (StringUtil.isNotEmpty(data.get("JE_SYS_CALENDAR_ID").toString())) {
                DynaBean bean = metaService.selectOne("JE_SYS_CALENDAR_PUSH", ConditionsWrapper.builder().eq("JE_SYS_CALENDAR_ID", data.get("JE_SYS_CALENDAR_ID").toString()), "JE_SYS_CALENDAR_PUSH_ID");
                DynaBean dynaBean = new DynaBean("JE_SYS_CALENDAR_PUSH", false);
                dynaBean.setStr("JE_SYS_CALENDAR_PUSH_ID", bean.getStr("JE_SYS_CALENDAR_PUSH_ID"));
                dynaBean.setStr("PUSH_TIME", data.get("CALENDAR_REMIND_TIME").toString());
                dynaBean.setStr("PUSH_STARTTIME", data.get("CALENDAR_STARTTIME").toString());
                dynaBean.setStr("PUSH_ENDTIME", data.get("CALENDAR_ENDTIME").toString());
                metaService.update(dynaBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return baseRespResult;

    }

    @Override
    @RequestMapping(value = "/doRemove", method = RequestMethod.POST)
    @Transactional
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        String ids = param.getIds();
        if (StringUtil.isNotEmpty(ids)) {
            metaService.delete("JE_SYS_CALENDAR_PUSH", ConditionsWrapper.builder().eq("JE_SYS_CALENDAR_ID", ids));
        }
        return super.doRemove(param, request);

    }

    /**
     * 获取我的任务节点
     * @param param
     */
    @RequestMapping(value = "/getMyTaskTree", method = RequestMethod.POST)
    public JSONObject getMyTaskTree(BaseMethodArgument param) {
        String excludes = param.getExcludes();
        JsonAssist jsonAssist = JsonAssist.getInstance();
        JSONTreeNode rootNode = calendarService.getMyTaskTree();
        return DirectJsonResult.buildObjectResult(jsonAssist.buildModelJson(rootNode, excludes.split(",")));
    }


    /**
     * 消息推送
     * @param param
     */
    @RequestMapping(value = "/warn", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult warn(BaseMethodArgument param, HttpServletRequest request) {
        calendarService.tasks();
        return BaseRespResult.successResult(null, "执行成功");
    }


}
